<template>
  <div class="cate-edit">
    <div v-if="!isCate">
      <Button type="warning" label="提交审核" @click="onSubmitClick" />
      <Button class="is-plain" label="取消" @click="onCancelClick" />
    </div>
    <el-form class="cateForm" :model="cateData.form" ref="formRef" status-icon :show-message="false" :label-width="110" label-position="left">
      <p class="title" v-if="!isCate">选择经营器械类别</p>

      <ApplyCate :isCate="isCate" :cates="cateData.selectedCate" @complete="onCompleteCate" />

      <div class="license" v-if="!isCate">
        <p class="title">上传证件</p>
        <div class="type">
          <div class="type-box" v-for="(cert, index) in cateData.form.certs" :key="index">
            <div class="checkBox-small">
              <el-checkbox v-model="cert.checked" :label="cert.title" size="large" />
            </div>

            <div v-if="cert.checked">
              <div class="checkBox-large">
                <div class="qulification">
                  <el-form-item label="上传证件照片" :prop="`certs[${index}].qualificationImg`" :required="true" class="item">
                    <div class="upload-img">
                      <el-upload class="avatar-uploader" accept=".jpg,.png,.jpeg" :action="actionUrl" :headers="headers" :show-file-list="false" :on-success="(res) => onUploadSuccess(cert, res)" :before-upload="beforeUpload">
                        <img v-if="cert.qualificationImg" :src="cert.qualificationImg" class="avatar" />
                        <div v-else class="noImg">
                          <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                          <div class="tip" scope.slot="tip">点击上传</div>
                        </div>
                      </el-upload>
                      <div class="tips">
                        <Link label="查看" class="btn" @click="onShowImgClick(cert.qualificationImg)" />
                        <p class="img-tip">只能上传jpg/png/jpeg文件，且不超过10MB</p>
                      </div>
                    </div>
                  </el-form-item>
                  <el-form-item v-if="cert.qualificationType !== 'MEDICAL_DEVICE_BUSINESS_RECORD_CERTIFICATE'" class="time" label="证件生效期" :prop="`certs[${index}].effectiveDate`" :required="true">
                    <el-date-picker v-model="cert.effectiveDate" type="date" placeholder="请选择开始时间" format="YYYY/MM/DD" value-format="YYYY/MM/DD" clearable />
                    <el-icon class="time-icon"><Minus /></el-icon><el-date-picker v-model="cert.expiredDate" class="time" type="date" placeholder="请选择到期时间" format="YYYY/MM/DD" value-format="YYYY/MM/DD" clearable />
                  </el-form-item>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-form>

    <Record v-if="isCate" :list="cateData.operateList" />
  </div>

  <el-image-viewer ref="previewViewer" v-if="showImageViewer" @close="closeImgView" :url-list="srcList" />
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Minus } from '@element-plus/icons-vue'
import { apiBasePath } from '@/api/config'
import api from '@/api'
import consts from '@/consts'
import Button from '@/components/button/button.vue'
import Link from '@/components/button/link.vue'
import Record from './components/record.vue'
import ApplyCate from '@/components/cate/index.vue'

const props = defineProps(['isCate'])
const emit = defineEmits(['complete', 'change'])

const router = useRouter()

const cateData = reactive({
  operateList: [],
  catIdList: [],
  selectedCate: [],
  form: {
    selected: [],
    certs: consts.qualificationType.map((e) => {
      return {
        ...e,
        checked: false,
        qualificationImg: '',
        effectiveDate: '',
        expiredDate: '',
        customerQualificationId: ''
      }
    })
  }
})

const formRef = ref(null)
let oldCustomerQualicaList = []

const showImageViewer = ref(false)
const srcList = ref([])

const actionUrl = apiBasePath + '/medinstrument/site/uploadSingleFile'

const headers = {
  Authorization: 'Bearer ' + localStorage.getItem('_site_token')
}

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg'
  const isLt1M = file.size / 1024 / 1024 < 10

  if (!isJPG) {
    ElMessage.error('只能上传jpg/png/jpeg文件!')
  }
  if (!isLt1M) {
    ElMessage.error('上传图片大小不能超过 10MB!')
  }
  return isJPG && isLt1M
}

const onUploadSuccess = (cert, res) => {
  cert.qualificationImg = res.data
}

const audit = async () => {
  let customerQualificationEditFormList = cateData.form.certs
    .filter((e) => e.checked === true)
    .map((e) => {
      return {
        qualificationImg: e.qualificationImg,
        expiredDate: e.expiredDate,
        effectiveDate: e.effectiveDate,
        qualificationType: e.qualificationType,
        customerQualificationId: e.customerQualificationId
      }
    })

  const params = { catIdList: cateData.catIdList, customerQualificationEditFormList }
  let { err } = await api.post('/medinstrument/site/customer/updateCustomerCat', params)
  if (err) {
    ElMessage.error(err)
  } else {
    ElMessage.success('采购商变更类目申请成功')
    emit('complete')
    infoData()
  }
}

const infoData = async () => {
  let { data, err } = await api.get('/medinstrument/site/customer/information')
  if (err) {
    ElMessage.error(err)
  } else {
    cateData.selectedCate = data.apparatusCategoryIds.map((e) => e)

    const customerQualificationList = data.customerQualificationList || []
    if (customerQualificationList.length > 0) {
      cateData.form.certs.forEach((cert) => {
        const qualification = customerQualificationList.find((e) => cert.qualificationType === e.qualificationType)
        if (qualification) {
          Object.assign(cert, { checked: true }, qualification)
        }
      })
    }

    cateData.catIdList = data.apparatusCategoryIds

    cateData.operateList = data.operateList
  }
}

const onSubmitClick = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      audit()
    }
  })
}

const onCancelClick = () => {
  emit('change')
}

const onCompleteCate = (val) => {
  cateData.catIdList = val
}

const onShowImgClick = (url) => {
  srcList.value = [url]
  showImageViewer.value = true
}

const closeImgView = () => {
  showImageViewer.value = false
}

onMounted(() => {
  infoData()
})
</script>

<style scoped lang="scss">
.cate-edit {
  .cateForm {
    .title {
      height: 20px;
      font-weight: 600;
      margin: 30px 0 10px 0;
    }

    .category {
      display: flex;
      align-items: center;
      margin-bottom: 0;

      .cates {
        width: 100%;
        padding: 20px 0;
        border-bottom: 1px dashed rgba(220, 223, 230, 1);

        .cateItems {
          width: 250px;

          .el-checkbox__label {
            text-overflow: ellipsis;
            overflow: hidden;
          }
        }
      }
    }
  }

  .license {
    .type {
      .type-box {
        border: 1px solid #dcdfe6;
        margin-bottom: 20px;
        border-radius: 4px;
      }

      .checkBox-small {
        display: flex;
        align-items: center;
        background-color: #fafafa;
        height: 48px;
        line-height: 16px;
        padding-left: 20px;
        border-radius: 4px;
      }

      .checkBox-large {
        .qulification {
          color: #606266;
          padding-left: 10px;

          .el-form-item {
            margin: 0;
          }

          .item {
            margin: 20px 0;

            .upload-img {
              display: flex;
              align-items: flex-end;

              .tips {
                display: flex;
                align-items: center;

                .btn {
                  margin-left: 10px;
                }

                .img-tip {
                  font-size: 12px;
                  color: var(--span-color-text);
                  height: 16px;
                  line-height: 16px;
                  margin-left: 12px;
                }
              }

              .noImg {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                width: 80px;
                height: 80px;

                .el-icon svg {
                  width: 25px;
                  height: 25px;
                  margin-bottom: 10px;
                }

                .tip {
                  font-size: 12px;
                  line-height: 12px;
                  padding: 0 5px;
                  text-align: center;
                }
              }
            }
          }

          .time {
            margin-bottom: 30px;

            .time-icon {
              font-size: 8px;
              margin: 0 11px;
              color: var(--span-color-text);
            }
          }
        }
      }
    }
  }
}
</style>
